// 生产环境

import fs from 'node:fs'
import * as electronBuilder from 'electron-builder'
import path from 'node:path'

export const ElectronBuildPlugin = () => {
  return {
    name: 'vite-plugin-electron-build',
    closeBundle() {
      const json = JSON.parse(fs.readFileSync('package.json', 'utf-8'))
      json.main = 'main.js'
      fs.writeFileSync('dist/package.json', JSON.stringify(json, null, 4))
      fs.copyFileSync(path.join('electron', 'main.js'), 'dist/main.js')
      fs.copyFileSync(path.join('electron', 'preload.js'), 'dist/preload.js')

      fs.mkdirSync('dist/node_modules', { recursive: true })

      electronBuilder.build({
        config: {
          directories: {
            output: path.resolve(process.cwd(), 'release'),
            app: path.resolve(process.cwd(), 'dist'),
          },
          //   asar: true,

          appId: 'com.example.app',
          productName: 'vite-electron',
          nsis: {
            oneClick: false, //  是否一键安装
            allowToChangeInstallationDirectory: true, // 允许用户选择安装目录
          },
          electronDownload: {
            mirror: 'https://npmmirror.com/mirrors/electron/',
          },
        },
      })
    },
  }
}
